package com.qf.hsr.controller;

import com.qf.hsr.entity.ResultVO;
import com.qf.hsr.pojo.User;
import com.qf.hsr.service.IUserService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author q
 * @version V1.0
 * @date 2021/11/16
 **/
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    /**
     * 查全部用户
     * @return
     */
    @RequestMapping("/findAll")
    public ModelAndView findAllUser(){
        ResultVO<List<User>> vo = userService.findAllUser();
        ModelAndView mav = new ModelAndView();
        mav.setViewName("user/user-list");
        mav.addObject("alluser",vo.getData());
        return mav;
    }

    /**
     * 根据id删除用户
     * @param userId
     * @return
     */
    @DeleteMapping("/deleteUserById/{userId}")
    @ResponseBody
    public ResultVO deleteUserById(@PathVariable("userId") Integer userId){
        return userService.deleteUserById(userId);
    }

    /**
     * 跳转到新增用户页面
     * @return
     */
    @RequestMapping("/toUserSave")
    public ModelAndView toUserSave(){
        ModelAndView mav = new ModelAndView();
        mav.setViewName("user/user-save");
        return mav;
    }

    /**
     * 新增用户
     * @param request
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @PostMapping("/saveUser")
    public ModelAndView saveUser(HttpServletRequest request) throws InvocationTargetException, IllegalAccessException {
        //System.out.println(request.getParameterMap());
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        BeanUtils.populate(user,parameterMap);
        user.setIsAdmin(0);
        user.setUserStatus(1);
        user.setUserCreateTime(new Date());
        user.setUserUpdateTime(new Date());
        user.setIsDelete(0);
        System.out.println(user);
        userService.saveUser(user);
        return this.findAllUser();
        /*ModelAndView mav = new ModelAndView();
        mav.setViewName("user/user-list");
        return mav;*/
    }

}
